package com.hfh.jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @Author hfh
 * @Date 2022 09 18 16 18
 **/
public class JDBCTest1 {
    public static void main(String[] args) {
        Map<String,String> loginMap = initUI();
        boolean loginSuccess = login(loginMap);
        System.out.println(loginSuccess ? "登录成功" : "登录失败");

    }

    private static boolean login(Map<String, String> loginMap) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        boolean loginSuccess = false;
        String loginName = loginMap.get("loginName");
        String loginPwd = loginMap.get("loginPwd");
        try {
            Class.forName("com.mysql.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/poetry";
            String user = "root";
            String password = "123456";
            con = DriverManager.getConnection(url,user,password);

            String sql = "select * from logininfo where loginName = ? and loginPwd = ?";
            ps = con.prepareStatement(sql);
            ps.setString(1,loginName);
            ps.setString(2,loginPwd);
            rs = ps.executeQuery();

            if (rs.next()){
                loginSuccess = true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return loginSuccess;
    }

    private static Map<String, String> initUI() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入登录名");
        String loginName = sc.nextLine();
        System.out.println("请输入登录密码");
        String loginPwd = sc.nextLine();

        Map<String,String> loginMap = new HashMap<>();
        loginMap.put("loginName",loginName);
        loginMap.put("loginPwd",loginPwd);

        return loginMap;
    }
}
